package com.huanzhu.asuper.supervisionapp.cjbjdudao.uitls;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.net.http.SslError;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ListAdapter;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.huanzhu.asuper.supervisionapp.cjbjdudao.R;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 功能说明：
 * 创建人： lijian.89
 * 创建时间： 2017/10/9
 */

public class UIUtils {
    /***
     * 动态设置listview高度
     * @param listView
     */
    public static void setListViewHeight(Context context, ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        if (listAdapter == null) {
            // pre-condition
            return;
        }
        int totalHeight = 0;
        View view;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            view = listAdapter.getView(i, null, listView);
            //宽度为屏幕宽度
            int i1 = View.MeasureSpec.makeMeasureSpec(PhoneUtils.getWindowWidth(context),
                    View.MeasureSpec.EXACTLY);
            //根据屏幕宽度计算高度
            int i2 = View.MeasureSpec.makeMeasureSpec(i1, View.MeasureSpec.UNSPECIFIED);
            view.measure(i1, i2);
            totalHeight += view.getMeasuredHeight();
        }
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }


    /**
     * 全面屏沉浸状态栏
     *
     * @return
     */
    public static void SetStatusBarFullScreen(Window window, int statusColor) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            //设置状态栏颜色
            window.setStatusBarColor(statusColor);
        }
    }

    public static void tintStatusBar(@NonNull Activity activity) {
        Window window = activity.getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        GradientDrawable drawable = new GradientDrawable( );


    }

    /**
     * 设置状态栏字体图标为深色，需要MIUIV6以上
     *
     * @param window 需要设置的窗口
     * @param dark   是否把状态栏字体及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    public static boolean MIUISetStatusBarLightMode(Window window, boolean dark) {
        if ("V9".equals(getSystemProperty("ro.miui.ui.version.name"))) {
            return false;
        }
        boolean result = false;
        if (window != null) {
            Class clazz = window.getClass();
            try {
                int darkModeFlag = 0;
                Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                if (dark) {
                    extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
                } else {
                    extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
                }
                result = true;
            } catch (Exception e) {
                Log.d("riso", e.getStackTrace() + "'");
            }
        }
        return result;
    }

    /**
     * 设置状态栏图标为深色和魅族特定的文字风格
     * 可以用来判断是否为Flyme用户
     *
     * @param window 需要设置的窗口
     * @param dark   是否把状态栏字体及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    public static boolean FlymeSetStatusBarLightMode(Window window, boolean dark) {
        boolean result = false;
        if (window != null) {
            try {
                WindowManager.LayoutParams lp = window.getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                window.setAttributes(lp);
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }

    /**
     * 设置状态栏图标为深色和Android 原生的文字风格
     * 仅仅支持6.0系统以上
     *
     * @param window
     * @param dark
     * @return
     */
    public static boolean setAndroidOsSetStatusBarLightMode(Window window, boolean dark) {

        if (window != null && dark) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                return true;
            }
        }
        return false;
    }

    /**
     * 设置状态栏图标为浅色和Android 原生的文字风格
     * 仅仅支持6.0系统以上
     *
     * @param window
     * @param dark
     * @return
     */
    public static boolean setAndroidOsSetStatusBarWhite(Window window, boolean dark) {

        if (window != null && dark) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                return true;
            }
        }
        return false;
    }


    /**
     * 传入白色颜色让其着色 需要的颜色
     *
     * @param window
     * @param context
     * @param color
     */
    public static void setWhiteBarColor(Window window, Context context, int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(ContextCompat.getColor(context, color));
        }
    }

    /**
     * 传入颜色让其着色 需要的颜色
     *
     * @param window
     * @param context
     * @param color
     */
    public static void setBarColor(Window window, Context context, int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(ContextCompat.getColor(context, color));
        }
    }


    /**
     * 清楚掉FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS 让其可以着色
     *
     * @param window
     */
    public static void setClearBarColor(Window window) {
        window.clearFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    }


    /**
     * 设置基础白色背景状态栏 状态栏图标为深色
     *
     * @param window
     */
    public static void setBaseBarColor(Window window, Context context, int color) {
        if (FlymeSetStatusBarLightMode(window, true) || MIUISetStatusBarLightMode(window, true) || setAndroidOsSetStatusBarLightMode(window, true)) {
            setWhiteBarColor(window, context, color);
        } else {
            setClearBarColor(window);
        }
    }


    /**
     * 获取 Miui 的系统信息  miui 提供了获取版本号 和信号
     *
     * @param propName
     * @return
     */
    public static String getSystemProperty(String propName) {
        String line;
        BufferedReader input = null;
        try {
            Process p = Runtime.getRuntime().exec("getprop " + propName);
            input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
            line = input.readLine();
            input.close();
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return line;
    }

//    /**
//     * 通过imageWidth 的宽度，自动适应高度
//     * * @param simpleDraweeView view
//     * * @param imagePath  Uri
//     * * @param imageWidth width
//     */
//    public static void setControllerListener(final SimpleDraweeView simpleDraweeView, String imagePath, final int imageWidth) {
//        final ViewGroup.LayoutParams layoutParams = simpleDraweeView.getLayoutParams();
//        ControllerListener controllerListener = new BaseControllerListener<ImageInfo>() {
//            @Override
//            public void onFinalImageSet(String id, @Nullable ImageInfo imageInfo, @Nullable Animatable anim) {
//                if (imageInfo == null) {
//                    return;
//                }
//                int height = imageInfo.getHeight();
//                int width = imageInfo.getWidth();
//                layoutParams.width = imageWidth;
//                layoutParams.height = (int) ((float) (imageWidth * height) / (float) width);
//                simpleDraweeView.setLayoutParams(layoutParams);
//            }
//
//            @Override
//            public void onIntermediateImageSet(String id, @Nullable ImageInfo imageInfo) {
//                Logger.d("TAGIntermediate image received");
//            }
//
//            @Override
//            public void onFailure(String id, Throwable throwable) {
//                throwable.printStackTrace();
//            }
//        };
//        DraweeController controller = Fresco
//                .newDraweeControllerBuilder()
//                .setControllerListener(controllerListener)
//                .setUri(Uri.parse(imagePath)).build();
//        simpleDraweeView.setController(controller);
//    }
//
//    public static void loadUri(String url, SimpleDraweeView draweeView, int width, int height) {
//        ImageRequest request =
//                ImageRequestBuilder.newBuilderWithSource(Uri.parse(url))
//                        .setResizeOptions(new ResizeOptions(width, height))
//                        //缩放,在解码前修改内存中的图片大小, 配合Downsampling可以处理所有图片,否则只能处理jpg,
//                        // 开启Downsampling:在初始化时设置.setDownsampleEnabled(true)
//                        .setProgressiveRenderingEnabled(true)//支持图片渐进式加载
//                        .setAutoRotateEnabled(true) //如果图片是侧着,可以自动旋转
//                        .build();
//
//        PipelineDraweeController controller =
//                (PipelineDraweeController) Fresco.newDraweeControllerBuilder()
//                        .setImageRequest(request)
//                        .setOldController(draweeView.getController())
//                        .setAutoPlayAnimations(true) //自动播放gif动画
//                        .build();
//
//        draweeView.setController(controller);
//    }

    public static void showLargePic(String url, WebView large) {
        //@TargetApi(11)
        large.setOverScrollMode(View.OVER_SCROLL_NEVER);
        large.getSettings().setJavaScriptEnabled(true);
        large.getSettings().setUseWideViewPort(true);
        large.getSettings().setLoadWithOverviewMode(true);
        large.getSettings().setBuiltInZoomControls(false);
        large.getSettings().setSupportZoom(false);
        large.getSettings().setDisplayZoomControls(false);

        large.setBackgroundResource(R.color.white_FFFFFF);
        large.setVerticalScrollBarEnabled(false);
        large.setHorizontalScrollBarEnabled(false);
        large.setWebViewClient(new WebViewClient(){
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }
        });
        large.loadUrl(url);
        large.setVisibility(View.VISIBLE);
    }
}
